import React from 'react';
import { connect } from 'dva';
import { Radio, Row, Card, Button, Form, Select, Input, Modal, message } from 'antd';
import { findDicByCodeSort } from '@/support/common';
import { isMobilePhone, isEmail } from 'validator';
import { routerRedux } from 'dva/router';
import CopyButton from '@/components/CopyButton';

const { Option } = Select;

const layout = {
  width: 400,
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const mapStateToProps = (state: any) => ({
  listData: state?.operationTools?.pageData,
  loading: state.loading.effects['operationTools/getFetchPage'],
  dicData: state?.menu?.dicData,
  userProfile: state?.menu?.userProfile,
});
const personnelDetail: React.FC = props => {
  const {
    dispatch,
    dicData,
    userProfile,
    location: { state = {} },
  } = props;
  const { formData, isEdit } = state;
  const operator = userProfile.userName;
  const { info } = Modal;

  const specityOptions = findDicByCodeSort(dicData, 'appOperationSpeciality');
  const stateOptions = findDicByCodeSort(dicData, 'appPersonnelState');
  const systemTypeOptions = findDicByCodeSort(dicData, 'appSystemType');

  const initialValues = isEdit
    ? formData
    : {
        nickname: '',
        phone: '',
        email: '',
        speciality: '',
        systemType: '0',
        mobileId: '',
        state: 0,
      };

  const [form] = Form.useForm();

  const goBack = () => {
    dispatch(routerRedux.push({ pathname: '/operationTools/appPersonnelManagement' }));
  };

  const handleAdd = values => {
    dispatch({
      type: 'operationTools/postObj',
      payload: {
        url: '/msuser/devopsuser',
        ...values,
        operator,
      },
      callback: res => {
        const pwd = res?.data?.password;

        info({
          icon: false,
          title: 'APP用户创建成功',
          onOk: goBack,
          okText: '确定',
          content: (
            <div>
              <p>手机号: {values.phone}</p>
              <p>
                密码: {pwd}
                <CopyButton value={pwd} />
              </p>
            </div>
          ),
        });
      },
    });
  };
  const handleUpdate = values => {
    dispatch({
      type: 'operationTools/putObj',
      payload: {
        url: '/msuser/devopsuser',
        id: formData.id,
        ...values,
      },
      callback: res => {
        message.success('APP用户修改成功');
        goBack();
      },
    });
  };

  const onFinish = (values: any) => {
    if (isEdit) {
      handleUpdate(values);
    } else {
      handleAdd(values);
    }
  };

  return (
    <Card>
      <Form
        {...layout}
        initialValues={initialValues}
        form={form}
        name="control-hooks"
        onFinish={onFinish}
        style={{ width: 600 }}
      >
        <Form.Item
          name="nickname"
          label="姓名"
          rules={[
            {
              required: true,
            },
            {
              validator: (_, text) => {
                if (text.length < 2 || text.length > 20) {
                  return Promise.reject('姓名长度在2-10之间');
                }
                return Promise.resolve();
              },
            },
          ]}
        >
          <Input placeholder="仅支持输入汉字、数字和英文字符" />
        </Form.Item>
        <Form.Item
          name="phone"
          label="手机号"
          rules={[
            {
              required: true,
              validator: (_, text) => {
                if (!isMobilePhone(text, 'zh-CN')) {
                  return Promise.reject('手机号格式错误');
                }
                return Promise.resolve();
              },
              message: '请输入正确的手机号',
            },
          ]}
        >
          <Input placeholder="请输入正确的手机号" disabled={isEdit} />
        </Form.Item>
        <Form.Item
          name="email"
          label="邮箱"
          rules={[
            {
              required: true,
              validator: (_, text) => {
                if (!isEmail(text)) {
                  return Promise.reject('邮箱格式错误');
                }
                return Promise.resolve();
              },
              message: '请输入正确的邮箱',
            },
          ]}
        >
          <Input placeholder="请填写正确的邮箱" />
        </Form.Item>
        <Form.Item name="speciality" label="使用专业" rules={[{ required: true }]}>
          <Select placeholder="请选择">
            {specityOptions.map(option => (
              <Option value={option.dictKey}>{option.dictValue}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="systemType" label="操作系统" rules={[{ required: true }]}>
          <Radio.Group allowClear>
            {systemTypeOptions.map(option => (
              <Radio value={option.dictKey}>{option.dictValue}</Radio>
            ))}
          </Radio.Group>
        </Form.Item>
        <Form.Item
          name="mobileId"
          label="设备唯一识别码"
          rules={[
            { required: true },
            {
              validator: (_, text) => {
                if (text.length > 100) {
                  return Promise.reject('最大支持输入100个字符');
                }
                return Promise.resolve();
              },
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item name="state" label="状态" rules={[{ required: true }]}>
          <Radio.Group>
            {stateOptions.map(option => (
              <Radio value={parseInt(option.dictKey)}>{option.dictValue}</Radio>
            ))}
          </Radio.Group>
        </Form.Item>
        <Form.Item>
          <Row justify="end">
            <Button key="cancel" style={{ marginRight: 12 }} htmlType="button" onClick={goBack}>
              取消
            </Button>
            <Button key="confirm" type="primary" htmlType="submit">
              确定
            </Button>
          </Row>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default connect(mapStateToProps)(personnelDetail);
